﻿using System;
using System.Linq;
using Soundteller.Audio.Model;
using Soundteller.Audio.Model.Interfaces;
using Soundteller.Audio.Repositories.Interfaces;

namespace Soundteller.Audio.Repositories
{
    public class SongRepository : MemoryRepositoryBase, ISongRepository
    {
        public SongRepository(IMemoryContext context)
            : base(context)
        {
        }

        public Song GetActiveSong()
        {
            return Context.ActiveSong;
        }

        public Song GetById(Guid songId)
        {
            return Context.Songs.SingleOrDefault(s => s.Id == songId);
        }

        public void Update(Song song)
        {
            if (song == null) throw new ArgumentNullException("song");
            if (Context.Songs.Count(s => s.Id == song.Id) != 1) throw new InvalidOperationException("Song not found");

            var index = Context.Songs.IndexOf(Context.Songs.Single(s => s.Id == song.Id));
            Context.Songs[index] = song;
        }

        public void Add(Song song)
        {
            if (song == null) throw new ArgumentNullException("song");
            if (Context.Songs.Any(s => s.Id == song.Id)) throw new InvalidOperationException("Duplicate song");

            Context.Songs.Add(song);
        }

        public void DeleteById(Guid songId)
        {
            if (Context.Songs.Count(s => s.Id == songId) != 1) throw new InvalidOperationException("Song not found");

            Context.Songs.Remove(Context.Songs.Single(s => s.Id == songId));
        }

        public void UpdateActiveSong(Song song)
        {
            if (song == null) throw new ArgumentNullException("song");

            Context.ActiveSong = song;
        }
    }
}